package com.jyh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.common.CustomException;
import com.jyh.dto.DishDto;
import com.jyh.mapper.DishMapper;
import com.jyh.pojo.Dish;
import com.jyh.pojo.DishFlavor;
import com.jyh.service.DishFlavorService;
import com.jyh.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    //保存菜品和口味
    @Override
    @Transactional
    public void saveDishAndFlavor(DishDto dishDto) {
        //自动拆箱已封装好的dish
        this.save(dishDto);

        //设置dishID,dishFlavor需要
        Long dishId = dishDto.getId();

        //获取flavor集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors ) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);
    }

    //查询菜品和口味
    @Override
    public DishDto getDishAndFlavor(Long id) {
        //获取菜品
        Dish dish = this.getById(id);
        //更加菜品id查询口味信息
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(lqw);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);
        return dishDto;

    }

    //更新
    @Override
    @Transactional
    public void updateDishAndFlavor(DishDto dishDto) {
        //更新菜品表
        this.updateById(dishDto);

        //口味表根据菜品id删除所有的口味信息
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);

        //根据菜品id插入口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor :flavors ) {
            //设置口味对应的菜品id
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

    //删除
    @Override
    public void deleteDishAndFlavor(List<Long> ids) {
        //需要删除的菜品必须是在停售情况下才能删除
        LambdaQueryWrapper<Dish>lqw1 =new LambdaQueryWrapper<>();
        lqw1.eq(Dish::getStatus,1);
        lqw1.in(Dish::getId,ids);
        int count = this.count(lqw1);
        if(count>0){
            throw new CustomException("菜品停售后才能删除");
        }
        //删除菜品
        this.removeByIds(ids);

        //删除菜品对应的口味
        LambdaQueryWrapper<DishFlavor>lqw2 =new LambdaQueryWrapper<>();
        lqw2.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(lqw2);

    }
}
